package com.chi.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig{
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        bean.setSecurityManager(defaultWebSecurityManager);//设置安全管理器
        // 添加shiro的内置过滤器
        //        /*
        //            anon:无需认证就能访问
        //            authc:必须认证才能访问
        //            user:必须拥有记住我功能才能访问
        //            perms:拥有某个资源的权限才能访问
        //            role:拥有某个角色权限才能访问
        //         */
        Map<String, String> filterMap = new LinkedHashMap<>();
//        filterMap.put("/user/add","authc");
//        filterMap.put("/user/update","authc");
//        filterMap.put("/user/*","authc");

        filterMap.put("/user/add","perms[user:add]");//跳转到未授权页面
        filterMap.put("/user/update","perms[user:update]");
        filterMap.put("/user/*","authc");

        bean.setLoginUrl("/toLogin");//进入登录页面，没有权限登录时跳转
        bean.setUnauthorizedUrl("/noAuth");//进入未授权页面
        bean.setFilterChainDefinitionMap(filterMap);
        return bean;
    }

    @Bean(name = "securityManager")
    public DefaultWebSecurityManager defaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联UserRealm
       securityManager.setRealm(userRealm);
        return securityManager;
    }

    @Bean//用来整合shiro 和 thymeleaf
    public ShiroDialect shiroDialect(){
        return new ShiroDialect();
    }


}
